<template>
    <div class="sensitiveword">
        <h2 style="width:100%;text-align: center;line-height:60px;font-weight: 550">敏感词汇配置管理</h2>
        <Form ref="formInline" :model="info" :rules="infoRules" inline :label-width="80" >
            <Row class="main">
                <p class="title">敏感参数设置</p>
                <div class="content">
                    <div v-if="false">
                        <Col span="8">
                        <FormItem prop="score1" label='暴恐违禁：'>
                            <Input
                                class="w-input"
                                v-model="info.score1"
                                :maxlength="20"
                                placeholder="请输入敏感指数"
                            />
                            <label for="" style="color: #ff9966">备注：介于0~1之间，大于等于0，小于1</label>
                        </FormItem>                  
                        <FormItem prop="score4" label='恶意推广：'>
                            <Input
                                class="w-input"
                                v-model="info.score4"
                                :maxlength="20"
                                placeholder="请输入敏感指数"
                            />
                            <label for="" style="color: #ff9966">备注：介于0~1之间，大于等于0，小于1</label>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem prop="score2" label='文本色情：'>
                            <Input
                                class="w-input"
                                v-model="info.score2"
                                :maxlength="20"
                                placeholder="请输入敏感指数"
                            />
                            <label for="" style="color: #ff9966">备注：介于0~1之间，大于等于0，小于1</label>
                        </FormItem>
                        <FormItem prop="score5" label='低俗辱骂：'>
                            <Input
                                class="w-input"
                                v-model="info.score5"
                                :maxlength="20"
                                placeholder="请输入敏感指数"
                            />
                            <label for="" style="color: #ff9966">备注：介于0~1之间，大于等于0，小于1</label>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem prop="score3" label='政治敏感：'>
                            <Input
                                class="w-input"
                                v-model="info.score3"
                                :maxlength="20"
                                placeholder="请输入敏感指数"
                            />
                            <label for="" style="color: #ff9966">备注：介于0~1之间，大于等于0，小于1</label>
                        </FormItem>
                        <FormItem prop="score6" label='低俗灌水：'>
                            <Input
                                class="w-input"
                                v-model="info.score6"
                                :maxlength="20"
                                placeholder="请输入敏感指数"
                            />
                            <label for="" style="color: #ff9966">备注：介于0~1之间，大于等于0，小于1</label>
                        </FormItem>
                    </Col>
                    </div>
                    <Col span="8">
                        <FormItem prop="start" label='是否启用：'>
                            <i-switch v-model="info.start" :true-value="1" :false-value="0">
                                <span slot="open">是</span>
                                <span slot="close">否</span>
                            </i-switch>
                        </FormItem>
                    </Col>                        
                    <Col span="8">
                        <label class="ivu-form-item-label">敏感词涉及第三方服务配置:</label>
                            <a class="ivu-form-item-content" href='https://login.bce.baidu.com/' target='_blank' style='background-color: #5362E1; color: white; padding: 6px; border-radius: 20px;'>点击配置</a>
                    </Col>                        
                </div>               
            </Row>
            <Row class="main">
                <p class="title">词汇信息</p>
                <Col span="23">
                    <Input
                        style="width:200px;margin: 0 15px 15px 30px;"
                        v-model="keyword"
                        :maxlength="25"
                        @on-change="keywordChange()"
                        placeholder="请输入关键字全文检索"
                        id="keyword"
                    />
                    <Button type="primary" @click="search(keyword)" id="search" style="border-radius: 20px;margin: 0 15px 15px 0;font-size:14px">
                        检索定位
                    </Button>
                    <i class="req-icon"></i><span style="color:red;">词汇录入格式要求: 每行不超过20个字，不能有空格，一行一个词条</span>
                </Col>                
                <Col span="23">
                        <!-- <div class="search-highlight" v-html="contentShow"  style="width:100%;margin-left: 30px;border:solid 1px #999;"> -->
                            <template> 
                               <section>
                                    <textarea ref="textareas" v-model="info.sensitives"  id="textareaId" class="search-highlight" style="width:100%;margin-left: 30px;border:solid 1px #999;" :rows="15">  
                                    </textarea>
                                </section>
                            </template>
                        <!-- </div>   -->
                </Col>
                <Col span="24" style="margin:20px 0 20px 20px;" v-if="false">
                    <i class="req-icon"></i>提&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;示：敏感词汇与敏感词汇之间以 "<span style='color:#ff9966'>英文输入法</span>" 的逗号隔开,如：“词1,词2,词3”
                    <FormItem prop="sensitives">
                    </FormItem>
                </Col>
            </Row>
        </Form>
        <div style="width:100%;text-align:center">
            <Button type="primary" @click="submit('formInline')" :disabled='disabledSave'>
                <Icon type="ios-checkmark" style="margin-right: 5px" />保存
            </Button>
        </div>
    </div>
</template>
<script>
import api from "@/api/commonApi";
import { Avatar, Switch } from "view-design";
import SearchHighlight from 'vue-search-highlight'
const CLASS_NAME = 'search-hightlight'
export default {
    // 注册为子组件
    components: {
        'search-highlight': SearchHighlight
    },
    props: {
        content: {
            type: String,
            default: ''
        },
        // keyword: {
        //     type: String,
        //     default: ''
        // },
        highlightStyle: {
            type: String,
            default: 'background: #ffff00'
        },
        currentStyle: {
            type: String,
            default: 'background: #ff9632'
        }
    },
    data() {
        const validateScore = (rule, value, callback) => {
                if (value === '') {
                    return callback(new Error('敏感指数最小为0，不能为空'));
                }
                let reg = /^[0-9]+.?[0-9]*$/;
                if(!reg.test(value)){
                    callback(new Error('敏感指数必须为数字,且不能位负数'));
                }else{
                    if(value<0 || value>=1){
                        callback(new Error("敏感指数必须大于等于0或者小于1"))
                    }else{
                        let tmp = value.toString().split('.');
                        if(tmp[1] != undefined && tmp[1].length>4){
                            callback(new Error("小数点后只能保留4位或小于4位"))
                        }else{
                            callback();
                        }
                    }
                }
            };
        return {
            keyword: '',
            content: " ",
            lightIndex: 0,
            matchCount: 0,
            info: {
                id: null,
                sensitives: "",
                start: 1,
                score1: 0.0001,
                score2: 0.0001,
                score3: 0.0001,
                score4: 0.0001,
                score5: 0.0001,
                score6: 0.0001
            },
            pageNo: null,
            infoRules: {
                score1: [{validator:validateScore,trigger:'blur'}],
                score2: [{validator:validateScore,trigger:'blur'}],
                score3: [{validator:validateScore,trigger:'blur'}],
                score4: [{validator:validateScore,trigger:'blur'}],
                score5: [{validator:validateScore,trigger:'blur'}],
                score6: [{validator:validateScore,trigger:'blur'}]
            },
            disabledSave: false,
            itemcount:null,
            itemHCount:0
        };
    },
    computed: {
        contentShow () {
            this.content = this.info.sensitives
            if (!this.keyword) return this.content
            let reg = new RegExp(this.keyword, 'g')
            let stringList = this.content.split(reg)
            if (!stringList.length) return this.content
            let content = ''
            // for (let i = 0; i < stringList.length - 1; i++) {
            //     let style = i === this.lightIndex ? this.currentStyle : this.highlightStyle
            //     content += `${stringList[i]}<font style="${style}" ${CLASS_NAME}>${this.keyword}</font>`
            // }
            content += stringList[stringList.length - 1]
            return content;
        }
    },
    watch: {
    },
    created() {
        this.$axios.post(api.geSensitive,{}).then(resp => {
                if (resp.data.object) {
                    this.info = resp.data.object;
                } else {
                    this.info = {
                        id: null,
                        sensitives: "",
                        start: 1,
                        score1: 0.0001,
                        score2: 0.0001,
                        score3: 0.0001,
                        score4: 0.0001,
                        score5: 0.0001,
                        score6: 0.0001
                    }
                }
            })
            .catch(err => {
                this.$Message.error(resp.data.message)
            });
        this.content = this.info.sensitives
        // const index = this.content.indexOf(keyword)
        let breadList = [
            { path: "", title: "首页" },
            {
                path: "",
                title: "帐号权限配置"
            },
            {
                path: "",
                title: "敏感词汇"
            }
        ];
        this.$emit("changeBreadList", breadList);
    },
    components: { "i-switch": Switch },
    methods: {
        keywordChange(){
            this.itemcount=null;
            this.itemHCount=0;
        },
        //检索定位
        search(val){
            if(this.info.sensitives.indexOf(val)==-1){
                this.$Message.info("未检索到词汇!");
                return;
            }
            let content = this.info.sensitives.split(/[\s\n]/);
            let index = 0;
            let itemlength=0;
            if((this.itemHCount+1) >= content.length){
                this.keywordChange();
            }
            for(let i =0; i< content.length; i++){
                this.itemHCount = i;
                if(content[i].indexOf(val)!=-1 && ((!this.itemcount && this.itemcount!=0) || i>this.itemcount)){
                    index = i;
                    this.itemcount=i;
                    itemlength += content[i].indexOf(val);
                    break;
                }else{
                    itemlength += content[i].length+1;
                }
            }
            if(this.itemcount != this.itemHCount){
                this.keywordChange();
                this.search(val);
                return;
            }
            let node = this.$refs.textareas;
            node.selectionStart = parseInt(itemlength); 
            node.selectionEnd = (parseInt(itemlength)+parseInt(val.length));
            node.focus();
            let t1 = document.getElementById("textareaId");
            // 获取总行数
            let linesCount = 0;
            if (t1.value.indexOf("\r\n") >= 0){
                // IE 中使用 \r\n
                linesCount = t1.value.split("\r\n").length;
            }else{
                // Firefox、Chrome 中使用 \n，或当不存在换行时进入本代码
                linesCount = t1.value.split("\n").length;
            }
            // 要滚动到的行索引，第一行为 0
            t1.scrollTop = (index * t1.scrollHeight) / linesCount;
        },
        submit(name) {
            this.disabledSave = true
            this.$refs[name].validate(valid => {
                if (valid) {
                    let operateApi = "";
                    let params = {};
                    operateApi = api.sensitiveUpdate;
                    params.id = parseInt(this.info.id);
                    params.sensitives = this.info.sensitives.trim();
                    params.start = this.info.start;
                    params.score1 = parseFloat(this.info.score1);
                    params.score2 = parseFloat(this.info.score2);
                    params.score3 = parseFloat(this.info.score3);
                    params.score4 = parseFloat(this.info.score4);
                    params.score5 = parseFloat(this.info.score5);
                    params.score6 = parseFloat(this.info.score6);
                    this.$axios
                        .post(api.updateSensitive, params)
                        .then(resp => {
                            if (resp.data.success) {
                                this.$Message.info("保存成功");
                                setTimeout(() => {
                                    this.disabledSave = false
                                }, 7000);
                            } else {
                                this.$Message.error("保存失败，请重试");
                                setTimeout(() => {
                                    this.disabledSave = false
                                }, 7000);
                            }
                        })
                        .catch(err => {
                            console.log(err);
                            setTimeout(() => {
                                this.disabledSave = false
                            }, 7000);
                        });
                } else {
                    this.$Message.error("数据不正确");
                    setTimeout(() => {
                        this.disabledSave = false
                    }, 7000);
    }
            });
        }
    }
};
</script>
<style lang="less" scoped>
.sensitiveword {
    padding: 10px 0;
    width: 100%;
    background: #ffffff;
    box-sizing: border-box;
    .main{
        width: 98%;
        margin: 20px auto;
        margin-left: 1%;
        margin-bottom: 20px;
        border: 1px solid #f0f0f0;
        box-shadow: 0 4px 3px #ebedf8;
        border-radius: 5px;
        .content{
            margin-left: 10px;
        }
        .title {
            font-size: 20px;
            padding-left: 15px;
            margin-bottom: 20px;
            color: #333;
            height: 40px;
            line-height: 40px;
            background: #ebedf8;         
        }
    }
    .light-high{
      color: #ff00ff;
    }
    .padding-l {
        padding-left: 5px;
    }
    .padding-r {
        padding-right: 5px;
    }
    .padding-t {
        padding-top: 15px;
        font-weight: 700;
        font-size: 20px;
    }
    .padding-b {
        padding-bottom: 15px;
    }
    .borderRight {
        border-right: 1px solid #e5e5e5;
    }
    .borderLeft {
        border-left: 1px solid #e5e5e5;
    }
    .borderBottom {
        border-bottom: 1px solid #e5e5e5;
    }
    .borderTop {
        border-top: 1px solid #e5e5e5;
    }
    .w-select {
        width: 100px;
    }
    .w-input {
        margin-right: 20px;
    }
    .w-textarea {
        width: 100%;
        margin-left: 30px;
    }
    .req-icon {
        font-size: 18px;
        color: red;
        display: inline-block;
        height: 18px;
        width: 18px;
        text-align: center;
        line-height: 18px;
        vertical-align: middle;
    }
}
</style>
